<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: Asha
 * Date: 2016/11/4
 * Time: 10:16
 */
class Version extends MY_Controller
{
    var $url;
    var $appid;
    var $appkey;
    var $util;
    var $hostAndroid;
    var $downHost;
	var $docSafeDesc;
	var $iosDownLink;

    public function __construct()
    {

        parent::__construct();

        $this->url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms";
        $this->appid = "1400023853";
        $this->appkey = "7a77df74f4675c250c0d439d6fb1840e";

        $this->hostAndroid = "http://t.ejinshan.net/publish/android/";
        $this->downHost = "http://t.ejinshan.net/publish/";
		$this->iosDownLink = '';
		
        $this->util = new SmsSenderUtil();
    }

    public function index()
    { 
	   $this->load->helper('url');
       $this->load->view('admin/control_index.php');
      /*
        $data['error'] = "";
        $this->load->library('form_validation');
        $this->load->helper('url');
        $this->load->view("login/login.html",$data);
      */
    }

    public function get_newversion()
    {
        $result = array('result' => 0);
        $callback = ($this->input->get('callback')) ? trim($this->input->get('callback')) : "";
        //post
        //$callback = ($this->input->post('callback')) ? trim($this->input->post('callback')) : "";
        if ($callback == '') {
            echo $callback . '(' . json_encode($result) . ')';
            exit;
        } else {

            $this->load->model('version_model');
            $result = $this->version_model->newVersion();
            echo $callback . '(' . json_encode($result, JSON_UNESCAPED_UNICODE) . ')';
            exit;
        }
    }

    public function get_history()
    {
        $result = array('result' => 0, 'msg' => '参数不对');
        $type = ($this->input->get('type')) ? trim($this->input->get('type')) : "";
        $callback = ($this->input->get('callback')) ? trim($this->input->get('callback')) : "";
        //post
        //$type =  ($this->input->post('type')) ? trim($this->input->post('type')) : "";
        //$callback = ($this->input->post('callback')) ? trim($this->input->post('callback')) : "";
        if ($type == '' || $callback == '') {
            echo $callback . '(' . json_encode($result) . ')';
            exit;
        } else {

            $this->load->model('version_model');
            if ($type == 'all') {
                $result = $this->version_model->historyAll($type);//echo '<pre>'; print_r($result); exit;
            } else {
                $result = $this->version_model->history($type);//echo '<pre>'; print_r($result); exit;
            }
            echo $callback . '(' . json_encode($result, JSON_UNESCAPED_UNICODE) . ')';
            exit;
        }
    }

    public function check_version()
    {
        $result = array('result' => 0);
        $type = ($this->input->get('type')) ? trim($this->input->get('type')) : "";
        $cversion = ($this->input->get('current_version')) ? trim($this->input->get('current_version')) : "";

       // $cversion = ($this->input->post('current_version')) ? trim($this->input->post('current_version')) : "";
        // $type = ($this->input->post('type')) ? trim($this->input->post('type')) : "";

        if ($type == '' || $cversion == '') {
            echo json_encode($result,JSON_UNESCAPED_SLASHES);
            exit;
        } else {

            $this->load->model('version_model');
            $result = $this->version_model->checkverion($type, $cversion);
            echo json_encode($result,JSON_UNESCAPED_SLASHES);
            exit;
        }
    }

    /**
     * desc:用于获取云文档首页的4个产品的下载连接
     **/
    public function get_downlink()
    {
        $callback = ($this->input->get('callback')) ? trim($this->input->get('callback')) : "";
        //$callback = ($this->input->post('callback')) ? trim($this->input->post('callback')) : "";
        $this->load->model('version_model');
        $result = $this->version_model->downlinks();
        echo $callback . '(' . json_encode($result) . ')';
        exit;

    }

    /**
     * desc:获得前端上传插件的版本连接
     * date: 04-18-2017
     * author: Asha
     */
    public function get_kislink(){
        $result = array();
        $result['result'] = 0;
        $result['url'] = '';
        $callback = ($this->input->get('callback')) ? trim($this->input->get('callback')) : "";
        $this->load->model('version_model');
        $downInfo = $this->version_model->downKisupload();

        if(!empty($downInfo)){
            $version = substr($downInfo[0]['version_no'],1);
            $url = $downInfo[0]['download_addr'];
            $returnUrl = $url.'#version='.$version;
            $result['result'] = 1;
            $result['url'] = $returnUrl;
        }

        echo $callback . '(' . json_encode($result,JSON_UNESCAPED_SLASHES) . ')'; exit;

    }

	/**
	* desc: upload save for version
	*/
	function uploadSave(){
		$post = ($this->input->post('savefile')) ? trim($this->input->post('savefile')) : "11111";
		if(!empty($post)){
			set_time_limit(25);
            //upload file

            $protype = ($this->input->post('protype')) ? trim($this->input->post('protype')) : "";
			$version = ($this->input->post('version')) ? trim($this->input->post('version')) : "";
			$modies = ($this->input->post('modi')) ? $this->input->post('modi') : "";
			
            //$config['upload_path']      = './uploads/'.$protype.'/'; //locale
			//$config['upload_path']      =  '/data/ejinshan.net/t/saas-www/saas.ejinshan.net/publish/'.$protype.'/';  //server
			$config['upload_path']  = '../saas-www/saas.ejinshan.net/publish/'.$protype.'/';
            $config['allowed_types']    = '*';
            $config['max_size']     = 20971520; //20M
          //  $config['max_width']        = 1024;
           // $config['max_height']       = 768;
		   $error = '';

		   if($protype == 'android'){
			    if(empty($version)){
                $error = "需要指定 Android 版本号！ ";
                }

				if(empty($modies[0])){
					$error = "需要添加 Android 版本 修改记录！ ";
					//
				}
                if (!isset($_FILES['userfile'])){
					$error = "安桌包 请上传包文件";
				}
		   }
		   
		    if($protype == 'iphone'){
				if(empty($version)){
                    $error = "需要指定 Iphone 版本号！ ";
                }

				if(empty($modies[0])){
					$error = "需要指定 Iphone 版本 修改记录！ ";
					//
				}
				$iossize = ($this->input->post('iossize')) ? trim($this->input->post('iossize')) : "";
				if(empty($iossize)){
                    $error = "需要指定 IOS APP 包大小！ ";
                }
			}
			
			if($protype == 'kisupload'){
				if(empty($version)){
                    $error = "需要指定 上传控件 版本号！ ";
                }
                if (!isset($_FILES['userfile'])){
					$error = "上传控件 请上传包文件"; 
				}

			}

		   
		   	if(!empty($error)){
				
			    $this->load->helper(array('form', 'url'));        
		        $this->load->helper('url');
				$this->load->view('upfile',  array('error' => $error ));
				
			}else{
				    $this->docSafeDesc['iphone'] = 'iPhone版';
		            $this->docSafeDesc['android'] = 'Android版';
		            $this->docSafeDesc['windows'] = '金山网盘PC版';
		            $this->docSafeDesc['web'] = '金山网盘WEB版';
					$this->docSafeDesc['kisupload'] = 'IE网页上传控件';
					$resultData = array();
					$resultData['产品类型'] = $this->docSafeDesc[$protype];
					$resultData['添加结果'] = '添加版本信息失败！';
										
					$desc = $this->docSafeDesc[$protype];							

					if(!empty($modies)){
						$mnum = count($modies);
						for($i=0;$i<$mnum;$i++){
							$n = $i+1;
							$modies[$i] = $n.'. '.$modies[$i];
						}
						$modiData = implode($modies,'===');
						
					}					
					$savedata = array();
					$savedata['pro_name'] = $protype;
					$savedata['version_no'] = 'V'.$version;
					$savedata['platform'] = '';
					$savedata['modify_content'] = $modiData;
					$savedata['modify_date'] = date('Y-m-d H:i:s');
					$savedata['create_date'] = date('Y-m-d H:i:s');
					$savedata['desc'] = $desc;
				
				if($protype == 'iphone'){
					//insert into docdiskversion db	due to IOS NO package for upload				
                    $savedata['size'] = $iossize;
					$savedata['download_addr'] = $this->iosDownLink;

					$this->load->model('version_model');
					$result = $this->version_model->saveVersionInfo($savedata);
					
				}
				if($protype == 'web'){
					//insert into version info due to no need upload package.
					$savedata['size'] = 0;
					$savedata['download_addr'] = '';
					$this->load->model('version_model');
					$result = $this->version_model->saveVersionInfo($savedata);
					
				}
				
				if($protype == 'kisupload' || $protype == 'android' || $protype == 'windows'){
					
					$this->load->library('upload', $config);

					if ( ! $this->upload->do_upload('userfile'))
					{
						$error = array('error' => $this->upload->display_errors());
                        $this->load->helper(array('form', 'url'));        
		                $this->load->helper('url');						
						$this->load->view('upfile', $error);
					}else{

						$resData = $this->upload->data();
						$size = round($resData['file_size']/1024, 2).'M';
						$fname = $resData['file_name'];
						$filePath = $config['upload_path'].$fname;
						$url = $this->downHost.$protype.'/'.$fname;

						if($protype == 'kisupload'){
							//this only for update the version data
							$savedata = array();
							$savedata['version_no'] = 'V'.$version;
							$savedata['download_addr'] = $url;
							$savedata['modify_date'] = date('Y-m-d H:i:s');

							$this->load->model('version_model');
							$result = $this->version_model->updateKisUploader($savedata,$protype);
							
						}else{
							//insert version info
							$savedata['size'] = $size;
							$savedata['download_addr'] = $url;

							$this->load->model('version_model');
							$result = $this->version_model->saveVersionInfo($savedata);							
						}

						}//end the up file error
					
					
				}//end need upload package
				
				if($result)
				{
					if(!isset($resData)){
					    $resultData['添加结果'] = '版本信息添加成功';	
					}else{
						$resultData = $resData;
					}
					
					$data = array('upload_data' => $resultData);
					$this->load->helper('url');
					$this->load->view('upload_success', $data);

				}else{
					echo exec("rm -f".$filePath);

					$error = "添加".$protype.$version."版本信息失败！ ";
					$this->load->helper(array('form', 'url'));        
		            $this->load->helper('url');
					$this->load->view('upfile', $error);

					}
				
			}//need handle the version info for upload and insert

        }
		
	}
	
	
    /**
     * desc: upload the package for android and window client package
     * date: 04-18-2017
     * author: Asha
     */
    function uploadfile(){
        $this->load->helper(array('form', 'url'));        
		$this->load->helper('url');
		if(strtolower($this -> uri -> segment(1)) == 'login') return false;

		if(empty($_SESSION['upfile_account'])) {
			$data['error'] = "请先登录！";
			//$this->load->view("login/login.html", $data);
			redirect('/login/login.html');
			return false;
		}else{

			$this->load->view('upfile.php', array('error' => '' ));
		}

    }



    /**
     * 检查验证码
     * @return array|bool
     */
    public function checkMsg()
    {

        $result = array('result' => 0);

        $callback = ($this->input->get('callback')) ? trim($this->input->get('callback')) : "";
        //$callback = ($this->input->post('callback')) ? trim($this->input->post('callback')) : "";

        $code = ($this->input->get('code')) ? trim($this->input->get('code')) : "";
        //$code = ($this->input->post('code')) ? trim($this->input->post('code')) : "";

        $phone = ($this->input->get('phone')) ? trim($this->input->get('phone')) : "";
        //$phone = ($this->input->post('phone')) ? trim($this->input->post('phone')) : "";

        if ($code == '') {
            $result['msg'] = '验证码不能为空！';
        }
        if ($phone == '') {
            $result['msg'] = '手机号不能为空！';
        } else {
            if (preg_match("/^13[0-9]{1}[0-9]{8}$|15[0189]{1}[0-9]{8}$|18[0-9]{9}$/", $phone)) {
                //验证通过
                $c = $this->session->userdata();
                if (strtolower ($c['mycode']) != strtolower($code)) {
                    $result['msg'] = '验证码错误！';
                } else {
                    $msg = "TimeOn云文档下载地址:";
                    $this->sendMsg($phone,$msg);
                    $this->session->unset_userdata('mycode');
                    $result = array('result' => 1, 'msg' => 'success');
                }
            } else {
                //手机号码格式不对
                $result['msg'] = '手机号格式不对！';

            }

        }

        echo $callback . '(' . json_encode($result, JSON_UNESCAPED_UNICODE) . ')';
        exit;
    }

    /**
     * desc: 获取验证码图片
     */
    public function get_codepic()
    {
        $this -> load ->library('captcha');
        $code = $this -> captcha -> getCaptcha();
        $this->session->set_userdata('mycode', $code);
        $this -> captcha -> showImg();
        exit();
    }
    /**
     * 发送验证码
     * @desc 手机验证码发送
     * @return boolean result true/false
     * 普通单发，明确指定内容，如果有多个签名，请在内容中以【】的方式添加到信息内容中，否则系统将使用默认签名
     * @param int $type 短信类型，0 为普通短信，1 营销短信
     * @param string $nationCode 国家码，如 86 为中国
     * @param string $phoneNumber 不带国家码的手机号
     * @param string $msg 信息内容，必须与申请的模板格式一致，否则将返回错误
     * @param string $extend 扩展码，可填空串
     * @param string $ext 服务端原样返回的参数，可填空串
     * @return string json string { "result": xxxxx, "errmsg": "xxxxxx" ... }，被省略的内容参见协议文档
     */
    function sendMsg($phone, $msg,$type=0, $nationCode=86, $extend = "", $ext = "")
    {
        /*
        请求包体
        {
            "tel": {
                "nationcode": "86",
                "mobile": "13788888888"
            },
            "type": 0,
            "msg": "你的验证码是1234",
            "sig": "fdba654e05bc0d15796713a1a1a2318c",
            "time": 1479888540,
            "extend": "",
            "ext": ""
        }
        应答包体
        {
            "result": 0,
            "errmsg": "OK",
            "ext": "",
            "sid": "xxxxxxx",
            "fee": 1
        }
        */
        $this->load->model('version_model');
        $version = substr($this->version_model->downAndroid(),1);
        $msg .= $this->hostAndroid.$version.'.apk';

        $random = $this->util->getRandom();
        $curTime = time();
        $wholeUrl = $this->url . "?sdkappid=" . $this->appid . "&random=" . $random;
        // 按照协议组织 post 包体
        $data = new \stdClass();
        $tel = new \stdClass();
        $tel->nationcode = "" . $nationCode;
        $tel->mobile = "" . $phone;
        $data->tel = $tel;
        $data->type = (int)$type;
        $data->msg = $msg;
        $data->sig = hash("sha256",
            "appkey=" . $this->appkey . "&random=" . $random . "&time=" . $curTime . "&mobile=" . $phone, FALSE);
        $data->time = $curTime;
        $data->extend = $extend;
        $data->ext = $ext;
        return $this->util->sendCurlPost($wholeUrl, $data);
    }

}

class SmsSenderUtil {
    function getRandom() {
        return rand(100000, 999999);
    }
    function calculateSig($appkey, $random, $curTime, $phoneNumbers) {
        $phoneNumbersString = $phoneNumbers[0];
        for ($i = 1; $i < count($phoneNumbers); $i++) {
            $phoneNumbersString .= ("," . $phoneNumbers[$i]);
        }
        return hash("sha256", "appkey=".$appkey."&random=".$random
            ."&time=".$curTime."&mobile=".$phoneNumbersString);
    }
    function calculateSigForTemplAndPhoneNumbers($appkey, $random, $curTime, $phoneNumbers) {
        $phoneNumbersString = $phoneNumbers[0];
        for ($i = 1; $i < count($phoneNumbers); $i++) {
            $phoneNumbersString .= ("," . $phoneNumbers[$i]);
        }
        return hash("sha256", "appkey=".$appkey."&random=".$random
            ."&time=".$curTime."&mobile=".$phoneNumbersString);
    }
    function phoneNumbersToArray($nationCode, $phoneNumbers) {
        $i = 0;
        $tel = array();
        do {
            $telElement = new \stdClass();
            $telElement->nationcode = $nationCode;
            $telElement->mobile = $phoneNumbers[$i];
            array_push($tel, $telElement);
        } while (++$i < count($phoneNumbers));
        return $tel;
    }
    function calculateSigForTempl($appkey, $random, $curTime, $phoneNumber) {
        $phoneNumbers = array($phoneNumber);
        return $this->calculateSigForTemplAndPhoneNumbers($appkey, $random, $curTime, $phoneNumbers);
    }
    function sendCurlPost($url, $dataObj) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($dataObj));
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($curl);
        if (false == $ret) {
            // curl_exec failed
            $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}";
        } else {
            $rsp = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp . " " . curl_error($curl) ."\"}";
            } else {
                $result = $ret;
            }
        }
        curl_close($curl);
        return $result;
    }


}
